package edu.uoc.tds.pac4.client.ss2;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.GridBagLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

import edu.uoc.tds.pac4.client.PanelClientInterface;
import edu.uoc.tds.pac4.client.ss2.GestorPantallaSS2.TipusPantalla;
import edu.uoc.tds.pac4.common.PantallaError;
import edu.uoc.tds.pac4.common.TDSLanguageUtils;
import edu.uoc.tds.pac4.beans.Event;
import edu.uoc.tds.pac4.common.GestioEventsException;
import edu.uoc.tds.pac4.interfaces.RemoteInterface;

/**
 * Pantalla que llista els events i en mostra un calendari
 */
public class PantallaLlistarEvents extends PantallaGestorEvents implements PanelClientInterface {

	private static final long serialVersionUID = 1L;
	private JPanel jPanelContainer = null;
	private JPanelFiltreCalendari jPanelFiltre = null;
	private JPanelCalendari jPanelCalendari = null;
	private JPanelEvents jPanelEvents = null;
	private JPanel jPanelAccions = null;
	private JButton jButtonNou = null;
	private JButton jButtonModificar = null;
	private JButton jButtonCancelar = null;
	private JButton jButtonAssistents = null;
	private GestorPantallaSS2 gestor = null;
	private Vector<Event> currentEvents = null;
	private final Dimension dimButton = new Dimension(135, 30);  //  @jve:decl-index=0:
	
	/**
	 * Constructor
	 */
	public PantallaLlistarEvents() {
		super();
		initialize();
	}

	/**
	 * Constructor que rep una referencia al servidor remot
	 * 
	 * @param remot
	 */
	public PantallaLlistarEvents(RemoteInterface remot, GestorPantallaSS2 gestor) {
		this.remot = remot;
		this.gestor = gestor;
		initialize();
	}

	/**
	 * Inicialitza la pantalla
	 */
	protected void initialize() {
		// this.setTitle("Pantalla.title");
	}

	/**
	 * This method initializes jPanelContainer
	 * 
	 * @return javax.swing.JPanel
	 */
	@Override
	public JPanel getJPanelContainer(Dimension dimension) {
		if (jPanelContainer == null) {
			GridBagConstraints gbcPanelFiltre = new GridBagConstraints();
			gbcPanelFiltre.gridx = 0;
			gbcPanelFiltre.gridy = 0;
			gbcPanelFiltre.gridwidth = 2;

			GridBagConstraints gbcPanelCalendari = new GridBagConstraints();
			gbcPanelCalendari.gridx = 0;
			gbcPanelCalendari.gridy = 1;
			gbcPanelCalendari.fill = GridBagConstraints.NONE;
			gbcPanelCalendari.ipadx = 20;
			gbcPanelCalendari.ipady = 20;
			gbcPanelCalendari.anchor = GridBagConstraints.FIRST_LINE_START;

			GridBagConstraints gbcPanelEvents = new GridBagConstraints();
			gbcPanelEvents.gridx = 1;
			gbcPanelEvents.gridy = 1;
			gbcPanelEvents.weightx = 1;
			gbcPanelEvents.weighty = 1;
			gbcPanelEvents.insets = new Insets(0, 10, 10, 10);
			gbcPanelEvents.fill = GridBagConstraints.BOTH;
			
			GridBagConstraints gbcPanelButtons = new GridBagConstraints();
			gbcPanelButtons.gridx = 1;
			gbcPanelButtons.gridy = 2;
			gbcPanelButtons.weightx = 1;
			gbcPanelButtons.weighty = 1;
			gbcPanelButtons.insets = new Insets(0, 10, 10, 10);
			gbcPanelButtons.fill = GridBagConstraints.BOTH;

			jPanelContainer = new JPanel();
			jPanelContainer.setSize(dimension);
			jPanelContainer.setLayout(new GridBagLayout());
			jPanelContainer.add(getJPanelFiltre(), gbcPanelFiltre);
			jPanelContainer.add(getJPanelCalendari(), gbcPanelCalendari);
			jPanelContainer.add(getJPanelEvents(), gbcPanelEvents);
			jPanelContainer.add(getJPanelAccions(), gbcPanelButtons);
		}
		// carrega les dades del calendari
		updateCalendar();
		
		return jPanelContainer;
	}

	/**
	 * This method initializes jPanelFiltre
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJPanelFiltre() {
		if (jPanelFiltre == null) {
			jPanelFiltre = new JPanelFiltreCalendari(this,
					JPanelFiltreCalendari.Disposicio.HORITZONTAL,
					gestor.getUniversitat(), gestor.getCentre());
		}
		return jPanelFiltre;
	}

	/**
	 * This method initializes jPanelCalendari
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJPanelCalendari() {
		if (jPanelCalendari == null) {
			jPanelCalendari = new JPanelCalendari(this, new Dimension(200, 170));
		}
		return jPanelCalendari;
	}
	
	/**
	 * This method initializes jPanelEvents
	 * 
	 * @return JPanelEvents
	 */
	private JPanelEvents getJPanelEvents() {
		if (jPanelEvents == null) {
			jPanelEvents = new JPanelEvents();
		}
		return jPanelEvents;
	}
	
	/**
	 * This method initializes jPanelButtons
	 * 
	 * @return JPanelEvents
	 */
	private JPanel getJPanelAccions() {
		if (jPanelAccions == null) {
			jPanelAccions = new JPanel();
			jPanelAccions.setLayout(new GridBagLayout());
			Insets defaultInsets = new Insets(0, 10, 0, 10);
			
			
			GridBagConstraints gbcButtonNou = new GridBagConstraints();
			gbcButtonNou.gridx = 0;
			gbcButtonNou.insets = defaultInsets;
			
			GridBagConstraints gbcButtonModificar = new GridBagConstraints();
			gbcButtonModificar.gridx = 1;
			gbcButtonModificar.insets = defaultInsets;
			
			GridBagConstraints gbcButtonCancelar = new GridBagConstraints();
			gbcButtonCancelar.gridx = 2;
			gbcButtonCancelar.insets = defaultInsets;
			
			GridBagConstraints gbcButtonAssistents = new GridBagConstraints();
			gbcButtonAssistents.gridx = 3;
			gbcButtonAssistents.insets = defaultInsets;

			jPanelAccions.add(getJButtonNou(), gbcButtonNou);
			jPanelAccions.add(getJButtonModificar(), gbcButtonModificar);
			jPanelAccions.add(getJButtonCancelar(), gbcButtonCancelar);
			jPanelAccions.add(getJButtonAssistents(), gbcButtonAssistents);
		}
		return jPanelAccions;
	}
	
	/**
	 * Inicialitza el button de crear nou event
	 * @return JButton
	 */
	private JButton getJButtonNou() {
		if(jButtonNou == null) {
			jButtonNou = new JButton();
			jButtonNou.setText(TDSLanguageUtils.getMessage("Client.PantallaLlistarEvents.CrearEvent"));
			jButtonNou.setPreferredSize(dimButton);
			jButtonNou.setMinimumSize(dimButton);
			jButtonNou.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					gestor.carregaPantalla(TipusPantalla.nouEvent, null);
				}
			});
		}
		return jButtonNou;
	}
	
	/**
	 * Inicialitza el button de modificar un event
	 * @return JButton
	 */
	private JButton getJButtonModificar() {
		if(jButtonModificar == null) {
			jButtonModificar = new JButton();
			jButtonModificar.setText(TDSLanguageUtils.getMessage("Client.PantallaLlistarEvents.ModificarEvent"));
			jButtonModificar.setPreferredSize(dimButton);
			jButtonModificar.setMinimumSize(dimButton);
			jButtonModificar.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					int i = jPanelEvents.getSelectedRow();
					if(i >= 0) {
						// comprovar que sigui del mateix centre que el secretari
						if(!currentEvents.get(i).getCentre().getCodi().equals(
								gestor.getCentre().getCodi()))
							new PantallaError("Client.PantallaLlistarEvents.modificarEvent", PantallaError.Tipus.WARNING);
						else if(!currentEvents.get(i).isActiu())
							new PantallaError("Client.PantallaLlistarEvents.modificarEventBaixa", PantallaError.Tipus.WARNING);
						else 
							gestor.carregaPantalla(TipusPantalla.modificarEvent, currentEvents.get(i));
					}
					else
						new PantallaError("Client.PantallaLlistarEvents.seleccioEvent", PantallaError.Tipus.WARNING);
				}
			});
		}
		return jButtonModificar;
	}
	
	/**
	 * Inicialitza el button de Cancelar un event
	 * @return JButton
	 */
	private JButton getJButtonCancelar() {
		if(jButtonCancelar == null) {
			jButtonCancelar = new JButton();
			jButtonCancelar.setText(TDSLanguageUtils.getMessage("Client.PantallaLlistarEvents.CancelarEvent"));
			jButtonCancelar.setPreferredSize(dimButton);
			jButtonCancelar.setMinimumSize(dimButton);
			jButtonCancelar.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					int i = jPanelEvents.getSelectedRow();
					if(i >= 0) {
						// comprovar que sigui del mateix centre que el secretari
						if(!currentEvents.get(i).getCentre().getCodi().equals(
								gestor.getCentre().getCodi()))
							new PantallaError("Client.PantallaLlistarEvents.modificarEvent", PantallaError.Tipus.WARNING);
						else if(!currentEvents.get(i).isActiu())
							new PantallaError("Client.PantallaLlistarEvents.modificarEventBaixa", PantallaError.Tipus.WARNING);
						else
						{
							// Mostra el dialeg
							new JOptionPane();
							String motiu = (String)JOptionPane.showInputDialog(jPanelEvents, 
									TDSLanguageUtils.getMessage("Client.PantallaLlistarEvents.Motiu"),
									TDSLanguageUtils.getMessage("Client.PantallaLlistarEvents.CancelarEvent"),
									JOptionPane.PLAIN_MESSAGE);
							if(motiu != null)
								try {
									remot.cancelarEvent(currentEvents.get(i), motiu);
									// confirma el borrat
									new PantallaError("Client.PantallaLlistarEvents.cancelarOK", PantallaError.Tipus.INFO);
									updateCalendar();
								} catch (RemoteException e) {
									new PantallaError("Remote.Error", PantallaError.Tipus.ERROR);
								} catch (GestioEventsException e) {
									new PantallaError(e.getMessage(), PantallaError.Tipus.ERROR);
								}
						}
					}
					else
						new PantallaError("Client.PantallaLlistarEvents.seleccioEvent", PantallaError.Tipus.WARNING);
				}
			});
		}
		return jButtonCancelar;
	}
	
	/**
	 * Inicialitza el button de veure assistents d'un event
	 * @return JButton
	 */
	private JButton getJButtonAssistents() {
		if(jButtonAssistents == null) {
			jButtonAssistents = new JButton();
			jButtonAssistents.setText(TDSLanguageUtils.getMessage("Client.PantallaLlistarEvents.VeureAssistents"));
			jButtonAssistents.setPreferredSize(dimButton);
			jButtonAssistents.setMinimumSize(dimButton);
			jButtonAssistents.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					int i = jPanelEvents.getSelectedRow();
					if(i >= 0) {
						// comprovar que sigui del mateix centre que el secretari
						if(!currentEvents.get(i).getCentre().getCodi().equals(
								gestor.getCentre().getCodi()))
							new PantallaError("Client.PantallaLlistarEvents.AssistentsEventMateixCentre", PantallaError.Tipus.WARNING);
						else if(currentEvents.get(i).getDataFi().compareTo(Calendar.getInstance().getTime()) > 0)
							new PantallaError("Client.PantallaLlistarEvents.assistentsDataFi", PantallaError.Tipus.WARNING);
						else if(!currentEvents.get(i).isActiu())
							new PantallaError("Client.PantallaLlistarEvents.assistentsDeBaixa", PantallaError.Tipus.WARNING);
						else 
							gestor.carregaPantalla(TipusPantalla.assistentsEvent, currentEvents.get(i));
					}
					else
						new PantallaError("Client.PantallaLlistarEvents.seleccioEvent", PantallaError.Tipus.WARNING);
				}
			});
		}
		return jButtonAssistents;
	}

	/**
	 * Actualitza el contingut del calendari i la taula
	 */
	public void updateCalendar() {
		
		Date dataInici = null;
		Date dataFi = null;
		try {
			dataInici = jPanelCalendari.getDateInici();
			dataFi = jPanelCalendari.getDateFinal();
		} catch (ParseException e) {
			new PantallaError("Client.errorIntern", PantallaError.Tipus.ERROR);
		}
		// crida al servidor per rebre els events
		try {
			currentEvents = remot.getEvents(jPanelFiltre.getUniversitat(),
					jPanelFiltre.getCentre(), dataInici, dataFi, jPanelFiltre.getActius());
		} catch (RemoteException e) {
			new PantallaError("Remote.Error", PantallaError.Tipus.ERROR);
		} catch (GestioEventsException e) {
			new PantallaError(e.getMessage(), PantallaError.Tipus.ERROR);
		}
		jPanelEvents.drawEvents(currentEvents);
		jPanelCalendari.drawCalendar(currentEvents);
	}
}
